/**
 * 下载按钮
 */

var NativeApp = require("../phonegap/native-bridge.js");
var Stat = require("../utils/stat.js");

/**
 * 按钮类
 * @param  {Object} gameInfo  游戏信息
 * @param  {Object} pkgInfo   包信息
 * @param  {Element} element  zepto的html dom实例
 */
var ButtonUI = function(gameInfo, pkgInfo, element){
  var self = this;
  self.gameInfo = gameInfo;
  self.pkgInfo = pkgInfo;
  self.element = element;
  if(pkgInfo){
    //注册客户端的回调事件
    NativeApp.registerDownloadStateChangeListener(function (gameId, pkgName, state){
      console.log('registerDownloadStateChangeListener: ' + state);
      self.changeState(gameId, pkgName, state);
    });
    //初始化按钮状态
    NativeApp.getPackageState(pkgInfo.gameId, pkgInfo.packageName, pkgInfo.versionCode, function(result){
      if(result){
        self.changeState(pkgInfo.gameId, pkgInfo.packageName, result.state);
      }
    });
    // console.log(pkgInfo)
    // self.changeState(self.pkgInfo, self.pkgInfo, '5');
  }else{
    console.log('no pkgInfo');
  }
  return self; 
};

module.exports = ButtonUI;

/**
 * 切换按钮状态
 */
ButtonUI.prototype.changeState = function(gameId, pkgName, state){
  var self = this;
  var btn = self.element;
  btn.off('tap');
  console.log('change state to:' + state);
  //console.log(JSON.stringify(self.pkgInfo));
  switch(state.toString()){
    case '0':
        //状态:本地不存在此应用, 应提示下载 
        btn.text('下载').on('tap', function(){
          console.log('download event')
          
          NativeApp.downloadApp2(self.pkgInfo, function(){
            //变为正在下载
            console.log('call suc: downloadApp2')
            self.changeState(gameId, pkgName, '3'); 
            Stat.addActionStat("btn_down", "tj", gameId);
            //NativeApp.showMessage(gameId)
          });
        });
        break;

    //状态:已安装,提示打开
    case '1':
    case '2':
        btn.text('打开').on('tap', function(){
          console.log('openApp');
          NativeApp.startupNativeApp(self.pkgInfo.packageName);
        });
        break;

    //状态:正在下载,提示暂停
    case '3':
        btn.text('暂停').on('tap', function(){
          console.log('pause');
          //变为继续
          self.changeState(gameId, pkgName, '4');
          NativeApp.stopDownloadTask(gameId, self.pkgInfo.packageName);
        });
        break;

    //状态:下载任务被暂停,提示继续
    case '4':
        btn.text('继续').on('tap', function(){
          console.log('resume');
          NativeApp.resumeDownloadTask(gameId, self.pkgInfo.packageName, function(){
            //变为暂停
            self.changeState(gameId, pkgName, '3');
          });
        });;
        break;

    //状态:下载完成,提示安装
    case '5':
    case '6':
        btn.text('安装').on('tap', function(){
          console.log('installApp');
          NativeApp.installApp(self.pkgInfo.gameId, self.pkgInfo.packageName);
        });
        break;

    default:
        btn.text('未知');
        break;
  }
};